package com.cdks.wuxiu.api.util;


import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import cn.hutool.core.map.MapUtil;

import java.nio.charset.StandardCharsets;
import java.util.Map;


/**
 * Http 工具类
 */
@Slf4j
@Component
public class HttpUtils
{
    public static String send_get_request(String url, Map<String, String> headerMap, Map<String, String> paramMap)
    {
        return send_get_request(url, headerMap, MapUtil.join(paramMap, "&", "=", true));
    }

    public static String send_get_request(String url, Map<String, String> headerMap, String param)
    {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        if (headerMap != null)
        {
            headerMap.forEach((key, value) -> {
                headers.add(key, value);
            });
        }

        if (param != null)
        {
            url  = url + "?" + param;
        }

        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        log.info(response.toString());
        
        return response.getBody();
    }
    
    public static String send_post_request(String url, Map<String, String> headerMap, String body) {
        log.info(url + ": " + body);

        try
        {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
            if (headerMap != null)
            {
                headerMap.forEach((key, value) -> {
                    headers.add(key, value);
                });
            }

            //将请求头部和参数合成一个请求
            HttpEntity<String> entity = new HttpEntity<String>(body, headers);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            log.info(response.toString());

            return response.getBody();
        }
        catch (Exception e)
        {
            log.error(url + ": " + body);
            log.error(e.getMessage());
        }

        return null;
    }    
}
